package org.example.utils;
import org.cryptomator.siv.SivMode;
import org.cryptomator.siv.UnauthenticCiphertextException;

import javax.crypto.IllegalBlockSizeException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Arrays;
import java.util.Base64;

/**
 * @Author : Nico
 * @create 2025/4/22 13:15
 */
public class AesSivUtil {
    public static void main(String[] args) throws UnauthenticCiphertextException, IllegalBlockSizeException {
        // 1. 生成密钥（AES-256需32字节）
        byte[] keyBytes = new byte[]{98, 86, 71, 45, 27, -107, 53, -29, -62, 13, -110, 107, 106, -82, -51, 123, -45, -3, 25, 7, -44, -128, -39, -116, -76, -107, 96, 107, 2, -104, -100, -98}; // 32字节=256位
        // 生成随机密钥
//        new java.security.SecureRandom().nextBytes(keyBytes);
        SecretKey ctrKey = new SecretKeySpec(keyBytes, "AES"); // 加密密钥
        SecretKey macKey = new SecretKeySpec(keyBytes, "AES"); // 认证密钥（实际应分开生成）

        // 2. 初始化SIV模式
        SivMode siv = new SivMode();

        // 3. 加密（明文 + 可选关联数据）
        byte[] plaintext = "Hello, AES-SIV!".getBytes();
        byte[] associatedData = new byte[]{0x01, 0x02}; // 可选关联数据
        byte[] ciphertext = siv.encrypt(ctrKey, macKey, plaintext, associatedData);
        //[-44, -95, 103, 60, 44, -72, -41, 125, -85, -81, -100, 7, -118, -65, -11, -35, 33, 44, -35, 117, 114, -123, -26, 7, -62, -44, 79, 88, -126, 51, 38]
        System.out.println("加密结果: " + Arrays.toString(ciphertext));
        System.out.println("密文（Base64）: " + Base64.getEncoder().encodeToString(ciphertext));
//KFnPCy4132rr5wHir/13SEs3XVyheYHwtRPWIIzJg==
        // 4. 解密
        byte[] decrypted = siv.decrypt(ctrKey, macKey, ciphertext, associatedData);
        System.out.println("解密结果: " + new String(decrypted)); // 应输出原明文
    }
}
